package com.ruoyi.framework.web.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ruoyi.business.domain.WxUser;
import com.ruoyi.business.service.IWxUserService;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.uuid.IdUtils;

/**
 * 微信登录校验方法
 *
 * @author ruoyi
 */
@Component
public class WxLoginService
{
    private static final Logger log = LoggerFactory.getLogger(WxLoginService.class);

    @Autowired
    private TokenService tokenService;

    @Autowired
    private IWxUserService wxUserService;

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Autowired
    private RedisCache redisCache;

    /**
     * 微信小程序登录
     *
     * @param openid 微信openid
     * @return token
     */
    public String login(String openid)
    {
        // 参数校验
        if (StringUtils.isEmpty(openid))
        {
            log.info("微信登录失败：openid为空");
            throw new ServiceException("微信登录失败：openid为空");
        }

        try
        {
            // 查询用户
            WxUser wxUser = wxUserService.selectWxUserByOpenid(openid);
            if (wxUser == null)
            {
                log.info("微信用户不存在：openid={}", openid);
                throw new ServiceException("微信用户不存在");
            }

            // 获取用户详情
            LoginUser loginUser = (LoginUser) userDetailsService.loadUserByOpenid(openid);

            // 生成token
            return tokenService.createToken(loginUser);
        }
        catch (ServiceException e)
        {
            throw e;
        }
        catch (Exception e)
        {
            log.error("微信登录异常", e);
            throw new ServiceException("微信登录失败");
        }
    }
}